package com.gaohe.web.core.config;

import com.gaohe.common.utils.DateUtils;
import com.gaohe.scp.domain.CsAuction;
import com.gaohe.scp.domain.CsCar;
import com.gaohe.scp.service.ICsAuctionService;
import com.gaohe.scp.service.ICsCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
public class TimeTask {
    @Autowired
    private ICsCarService csCarService;
    @Autowired
    private ICsAuctionService auctionService;

    @Scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次
    public void execute(){
        Date nowDate = DateUtils.getNowDate();
        //查询所有状态为未开始/进行中的车辆
        List<CsCar> csCars = csCarService.selectCsCarListStatus();
        for (CsCar csCar : csCars) {
            if (Objects.equals(csCar.getStatus(), "未开始")){
                //判断时间 如果现在时间 > 开始时间，那么状态改为进行中
                if (nowDate.after(csCar.getStartTime())){
                    csCar.setStatus("进行中");
                    csCarService.updateCsCar(csCar);
                }
            }
            if (Objects.equals(csCar.getStatus(), "进行中")){
                //判断时间 如果现在时间 > 结束时间，那么状态改为已结束
                if (nowDate.after(csCar.getEndTime())){
                    csCar.setStatus("已结束");
                    csCarService.updateCsCar(csCar);
                    // 结算 car表的userId为当前车辆auction最高者的userId
                    List<CsAuction> csAuctions = auctionService.selectCsAuctionByCarId(csCar.getCarId());
                    if (csAuctions.size() != 0){
                        Long userId = csAuctions.get(0).getUserId();
                        csCar.setUserId(userId);
                        csCarService.updateCsCar(csCar);
                    }

                }
            }
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置日期格式
        System.out.println("欢迎访问 " + df.format(new Date()));
    }

}
